package org.sensornet2010.prototype;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.lang.*;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.RecordControl;
import javax.microedition.midlet.MIDlet;

public class SensorNetMobile extends MIDlet implements CommandListener{
	
	private static int RECORDING_INTERVAL = 4000; //3600
	private static int RECORDING_DURATION = 3000;
	private static int SEND_DATA_INTERVAL;
	
	private Display display;
	private Command exitCommand, startCommand, restartCommand, continueCommand, debugCommand, backCommand;
	
	private StringItem debugInfo;
	private byte[] sound;
	private Calendar date;
	
	private String str = "";

	
	
	public SensorNetMobile(){
		
		this.display = Display.getDisplay(this);
		this.exitCommand = new Command("Exit", Command.EXIT, 1);
		this.startCommand = new Command("Start", Command.OK, 1);
		this.restartCommand = new Command("Start", Command.OK, 1);
		this.continueCommand = new Command("Continue", Command.OK, 1);	
		this.debugCommand = new Command("Debug", Command.SCREEN, 1);
		this.backCommand = new Command ("Back", Command.BACK, 1);
		this.debugInfo = new StringItem("DEBUGINFO", "debug...");
	}
	
	
	public void startApp(){
		
		Form f = new Form("SensorNetMobile");
		
		f.addCommand(exitCommand);
		f.addCommand(startCommand);
		f.append("Welcome! We're going to measure the CO2 concentrations using your mobile phone.\n" +
				"Please, press 'Start' if you want to start the application.");
		f.setCommandListener(this);
		display.setCurrent(f);	
	}

	
	public void pauseApp(){
		
	}
	
	
	public void destroyApp(boolean unconditional){
		
	}
	
	
	public void commandAction(Command c, Displayable d) {
	
		if (c == this.exitCommand){
			destroyApp(false);
			notifyDestroyed();			
		} else if (c == this.startCommand){
			displayRecordingScreen();
			recordSound();
		} else if (c == this.continueCommand){
			displaySoundInfoScreen("");  
		} else if (c == this.restartCommand){   //PRESTATUUUUUUUUUUUUU!!!!!
			startApp();
		} else if (c == this.debugCommand){
			displayDebugScreen();
		} else if (c == this.backCommand){
			displaySoundInfoScreen(str);
		}
	}
	
	
	/*public void displayAccessRightsScreen(){
		
		Form f = new Form("ACCESS RIGHTS");
	
		access.addCommand(OkCommand);
		access.addCommand(exitCommand);
		access.append("To continue, we need to use the microphone of your mobile phone. Are you agree on?");
		access.setCommandListener(this); 
		display.setCurrent(f);	
		displayRecordingScreen();
	}*/
	
	
	public void displayRecordingScreen(){
		
		Form f = new Form("RECORDING");
		
		f.addCommand(exitCommand);
		f.setCommandListener(this);
		display.setCurrent(f);
	}
	
	public void displaySoundInfoScreen(String str){
		
		Form f = new Form("SOUND INFO");
		
		f.addCommand(exitCommand);
		f.addCommand(debugCommand);
		f.append(str);
		f.setCommandListener(this);
		display.setCurrent(f);	
	}
	
	public void displayDebugScreen(){ 
		
		Form f = new Form("DEBUG INFO");
		
	//	f.append(debugInfo);
		f.addCommand(backCommand);
		f.setCommandListener(this);
		display.setCurrent(f);
	}
	
	////////////////////////////////////////////////
	///////////////////////////////////////////////
	//////////////////////////////////////////////
	
	
	public void recordSound(){   
		
		Form f = new Form ("RECORDING");
		f.append(debugInfo);
		display.setCurrent(f);
		
		Thread t = new Thread(new Runnable(){
			public void run(){
				while(true){
				try{
					Player p = Manager.createPlayer("capture://audio");
					p.realize();
					// Get the RecordControl, set the record stream,
					// start the Player and record for 3 seconds.
					RecordControl rc = (RecordControl) p.getControl("RecordControl");
					ByteArrayOutputStream output = new ByteArrayOutputStream();
					rc.setRecordStream(output);
					rc.startRecord();
					p.start();	
					debugInfo.setText("Sound recording started...");
					Thread.sleep(RECORDING_DURATION);
					rc.commit();
					p.close();
					sound = output.toByteArray();
					
					analyseSound(sound);
					
					Thread.sleep(RECORDING_INTERVAL);
					
				} catch (IOException ioe) {
					debugInfo.setText("IOException" + ioe.getMessage());
				  } catch (MediaException me) {
					debugInfo.setText("MediaException" + me.getMessage());
				    } catch (InterruptedException ie) {
					debugInfo.setText("InterruptedException" + ie.getMessage());
				      }	
				}	
			}		
		});
		t.start();
	}
	
	public void analyseSound(byte[]sound){  
		
		byte a, b, k;

	//	str = str + "Sound recorded at, " + date + "\n" + "length: " + sound.length + "\n" + "\n";

		//a = sound[1013];
		//b = sound[1014];
		//k = a & b;
		a = 2;
		b = 6;
		int r = a&b;
		k = (byte) r;
		str = Integer.toBinaryString(k);
	//	str = Integer.toBinaryString(k) + Integer.toBinaryString(r);

		displaySoundInfoScreen(str);
	}
	
	public void sendSoundData(byte[] sound){
		///
	}	
	


}
